package com.op.teachingliteapp.sender.runnable;

import com.op.teachingliteapp.sender.handler.ScreenSendHandler;

import android.os.Looper;
import android.view.View;
import android.widget.Toast;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;


/**
 * Created by Genji on 2015/4/29.
 */
public class SenderRunnable implements Runnable {
    private String ip;
    private int port;
    private View view;

    public SenderRunnable(String ip, int port, View view) {
        this.ip = ip;
        this.port = port;
        this.view = view;

    }


    @Override
    public void run() {

        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {

                    ScreenSendHandler screenSendHandler = new ScreenSendHandler(view);


                    socketChannel.pipeline().addLast(screenSendHandler);
                }
            });
            ChannelFuture future = bootstrap.connect(ip, port).sync();
            future.channel().closeFuture().sync();

        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(view.getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
        }
        finally {
            Looper.prepare();
            group.shutdownGracefully();
            Looper.loop();

        }


    }
}
